﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Resources;
using System.Xml.Linq;

namespace SfdClient.Resources
{
    public class ResourceLocalizer
    {
        public ResourceLocalizer()
        {
            ApplyCulture(System.Threading.Thread.CurrentThread.CurrentUICulture.Name);
        }

        public void ApplyCulture(string cultureName)
        {
            try
            {

                StreamResourceInfo sri = GetStream(cultureName);

                _appStrings.Clear();
                var doc = XDocument.Load(sri.Stream);

                var elements = doc.Element("Resources").Elements("Resource");
                foreach (var xElement in elements)
                {
                    _appStrings.Add(xElement.Attribute("Key").Value, xElement.Value);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Impossible de trouver la ressource pour la culture {0}: {1}", cultureName, ex.Message));
            }
        }

        private static StreamResourceInfo GetStream(string cultureName)
        {
            try
            {
                return Application.GetResourceStream(
                    new Uri(
                       string.Format("/SfdClient;component/Resources/{0}.xml", cultureName), UriKind.Relative));
            }
            catch (IOException ex)
            {
                Trace.WriteLine(string.Format("Culture introuvable: {0}, langue française par défaut", cultureName));
                return Application.GetResourceStream(
                    new Uri("/SfdClient;component/Resources/fr-FR.xml", UriKind.Relative));
            }
        }

        private readonly Dictionary<string, string> _appStrings = new Dictionary<string, string>();

        public string this[string key]
        {
            get
            {
                //return _appStrings[key];
#if (DEBUG)
                return string.Format("@{0}@", _appStrings[key]);
#else
                return _appStrings[key];
#endif
            }
        }

        public static ResourceLocalizer Current
        {
            get { return Application.Current.Resources["localizer"] as ResourceLocalizer; }
        }
    }
}
